package com.kzy.demoadmin.web.utils;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.kzy.demoadmin.web.entity.User;
import com.kzy.demoadmin.web.exception.BizException;
import com.kzy.demoadmin.web.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 从请求头中获取token的value值
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 如果没拿到从参数中获取token的value值
            token = request.getParameter("token");
        }
        // 2. 开始执行认证
        if (StrUtil.isBlank(token)) {
            throw new BizException("无token，请重新登录");
        }
        // 获取 token 中的adminId
        String userId;
        User user;
        try {
            //解码，生成时放到Audience，现在拿出来
            userId = JWT.decode(token).getAudience().get(0);
            // 根据token中的userId查询数据库
            user = userService.findById(Integer.parseInt(userId));
        } catch (Exception e) {
            String errMsg = "token验证失败，请重新登录";
            log.error(errMsg + ", token=" + token, e);
            throw new BizException(errMsg);
        }
        if (user == null) {
            throw new BizException("用户不存在，请重新登录");
        }
        try {
            // 用户密码加密验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token); // 验证token是否合法
        } catch (JWTVerificationException e) {
            throw new BizException("token验证失败，请重新登录");
        }
        log.info("token验证成功，用户id：{}", userId);
        return true;
    }
}